<template>
  <div class="fullscreen text-center q-pa-md flex flex-center">
    <img
      src="/windows.svg"
      alt="Windows"
      class="q-mb-md"
      style="width: 120px"
    />
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { Notify, Loading, LoadingBar, QSpinnerIos } from "quasar";
import { initializeMsal } from "src/msal/authConfig";
import {
  getAccount,
  getAccessToken,
  handleRedirectCallback,
} from "src/msal/authService";
import { msalInstance, loginRequest } from "src/msal/authConfig";

LoadingBar.setDefaults({ color: "primary" });

Loading.setDefaults({
  spinner: QSpinnerIos,
  spinnerSize: 40,
  spinnerColor: "grey-8",
  backgroundColor: "grey-3",
});

const appConfig = ref({});

function handleResponse(response) {
  if (response !== null) {
    msalInstance
      .acquireTokenSilent({
        scopes: loginRequest.scopes,
        account: response.account,
      })
      .then((tokenResponse) => {
        console.log(
          "Access token acquired silently:",
          tokenResponse.accessToken
        );
        localStorage.setItem("token", tokenResponse.accessToken);
      })
      .catch((error) => {
        console.error("Silent token acquisition failed:", error);
        window.location.href = "/";
        return;
      });
  } else {
    window.location.href = "/";
  }
}

onMounted(async () => {
  const appConfigJSON = localStorage.getItem("appConfig");
  if (appConfigJSON) {
    appConfig.value = JSON.parse(appConfigJSON);
    if (
      !appConfig.value.clientId ||
      !appConfig.value.authority ||
      !appConfig.value.redirectUri
    ) {
      window.location.href = "/";
      return;
    }
    if (!window.location.hash.includes("code=")) {
      window.location.href = "/";
      return;
    }
    await initializeMsal();
    console.log("MSAL initialized with appConfig:", appConfig.value);
    Loading.show();

    msalInstance
      .handleRedirectPromise()
      .then(handleResponse)
      .catch((error) => {
        console.error(error);
      });
  }
});
</script>
